package com.apex.sdk.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apex.bluetooth.callback.GeneralCallback;
import com.apex.bluetooth.callback.WeatherCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apex.bluetooth.enumeration.QueryWatchInfoType;
import com.apex.bluetooth.model.EABleWeather;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivityTitanBinding;
import com.apex.sdk.databinding.ActivityTitanWeatherBinding;
import com.apex.sdk.databinding.AdapterTitanWeatherRecyclerviewBinding;
import com.apex.sdk.dialog.WaitingDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


public class TitanWeatherActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    private WaitingDialog waitingDialog;
    private EABleWeather eaBleWeather;
    private AdapterWeather adapterWeather;

    Calendar calendar;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x40) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                eaBleWeather = (EABleWeather) msg.obj;
                if (eaBleWeather == null) {
                    return;
                }
                activityTitanWeatherBinding.currentTemperature.setText(eaBleWeather.getCurrent_temperature() + "");
                activityTitanWeatherBinding.place.setText(eaBleWeather.getPlace());
                if (eaBleWeather.getS_day() == null || eaBleWeather.getS_day().isEmpty()) {
                    Toast.makeText(TitanWeatherActivity.this, getString(R.string.no_weather), Toast.LENGTH_SHORT).show();
                } else {
                    adapterWeather.notifyDataSetChanged();
                }

            } else if (msg.what == 0x41) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(TitanWeatherActivity.this, getString(R.string.failed_to_get_data), Toast.LENGTH_SHORT).show();
            } else if (msg.what == 0x42) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                activityTitanWeatherBinding.currentTemperature.setText(eaBleWeather.getCurrent_temperature() + "");
                activityTitanWeatherBinding.place.setText(eaBleWeather.getPlace());
                adapterWeather.notifyDataSetChanged();
            } else if (msg.what == 43) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(TitanWeatherActivity.this, getString(R.string.add_failed), Toast.LENGTH_SHORT).show();
            }
        }
    };
    ActivityTitanWeatherBinding activityTitanWeatherBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityTitanWeatherBinding = ActivityTitanWeatherBinding.inflate(getLayoutInflater());
        setContentView(activityTitanWeatherBinding.getRoot());
        activityTitanWeatherBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activityTitanWeatherBinding.tool);
        getSupportActionBar().setTitle(null);
        activityTitanWeatherBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(TitanWeatherActivity.this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        activityTitanWeatherBinding.weather.setLayoutManager(linearLayoutManager);
        adapterWeather = new AdapterWeather();
        activityTitanWeatherBinding.weather.setAdapter(adapterWeather);
        if (EABleManager.getInstance().getWatchType() == 1) {
            EABleConnectState state = EABleManager.getInstance().getDeviceConnectState();
            if (state == EABleConnectState.STATE_CONNECTED) {
                if (waitingDialog == null) {
                    waitingDialog = new WaitingDialog(TitanWeatherActivity.this);
                }
                waitingDialog.show();
                EABleManager.getInstance().queryWatchInfo(QueryWatchInfoType.weather, new WeatherCallback() {
                    @Override
                    public void weatherInfo(EABleWeather eaBleWeather) {
                        if (mHandler != null) {
                            Message message = mHandler.obtainMessage();
                            message.what = 0x40;
                            message.obj = eaBleWeather;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void mutualFail(int errorCode) {
                        if (mHandler != null) {
                            mHandler.sendEmptyMessage(0x41);
                        }
                    }
                });
            }
        }
        activityTitanWeatherBinding.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EABleManager.getInstance().getDeviceConnectState() == EABleConnectState.STATE_CONNECTED) {
                    if (eaBleWeather == null) {
                        eaBleWeather = new EABleWeather();
                        eaBleWeather.setPlace("jiaxiang");
                        eaBleWeather.setTemperatureUnit(EABleWeather.TemperatureUnit.centigrade);
                        eaBleWeather.setCurrent_temperature(20);
                        List<EABleWeather.EABleWeatherItem> weatherItemList = new ArrayList<>();
                        eaBleWeather.setS_day(weatherItemList);
                    }
                    List<EABleWeather.EABleWeatherItem> weatherItemList = eaBleWeather.getS_day();
                    eaBleWeather.setPlace("jiaxiang");
                    eaBleWeather.setCurrent_temperature(20);
                    if (weatherItemList == null) {
                        weatherItemList = new ArrayList<>();
                        eaBleWeather.setS_day(weatherItemList);
                    }
                    EABleWeather.EABleWeatherItem eaBleWeatherItem = new EABleWeather.EABleWeatherItem();
                    eaBleWeatherItem.setAir_humidity(80);
                    eaBleWeatherItem.setCloudiness(20);
                    eaBleWeatherItem.setE_day_type(EABleWeather.WeatherType.clear);
                    eaBleWeatherItem.setE_moon(EABleWeather.Moon.new_moon);
                    eaBleWeatherItem.setMax_temperature(26);
                    eaBleWeatherItem.setMin_temperature(15);
                    eaBleWeatherItem.setMax_wind_power(3);
                    eaBleWeatherItem.setMin_wind_power(1);
                    eaBleWeatherItem.setWind(3);
                    eaBleWeatherItem.setWindDirection(EABleWeather.WindDirection.NE);
                    eaBleWeatherItem.setAir_grade(30);
                    eaBleWeatherItem.setUv(8);
                    eaBleWeatherItem.setPm(1);
                    eaBleWeatherItem.setRain_pro(30);
                    eaBleWeatherItem.setPressure(3);
                    weatherItemList.add(eaBleWeatherItem);
                    if (waitingDialog == null) {
                        waitingDialog = new WaitingDialog(TitanWeatherActivity.this);
                    }
                    if (!waitingDialog.isShowing()) {
                        waitingDialog.show();
                    }
                    EABleManager.getInstance().setWeather(eaBleWeather, new GeneralCallback() {
                        @Override
                        public void result(boolean success, int reason) {
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x42);
                            }
                        }

                        @Override
                        public void mutualFail(int errorCode) {
                            if (mHandler != null) {
                                mHandler.sendEmptyMessage(0x43);
                            }
                        }
                    });

                }
            }
        });
    }

    @Override
    protected void onDestroy() {

        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        adapterWeather = null;

        super.onDestroy();
    }

    class AdapterWeather extends RecyclerView.Adapter<AdapterWeather.HoldView> {
        @NonNull
        @Override
        public HoldView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            AdapterTitanWeatherRecyclerviewBinding adapterTitanWeatherRecyclerviewBinding = AdapterTitanWeatherRecyclerviewBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new HoldView(adapterTitanWeatherRecyclerviewBinding);

        }

        @Override
        public void onBindViewHolder(@NonNull HoldView holder, int position) {
            if (eaBleWeather == null || eaBleWeather.getS_day() == null || eaBleWeather.getS_day().isEmpty()) {
                return;
            }
            EABleWeather.EABleWeatherItem weatherItem = eaBleWeather.getS_day().get(position);
            EABleWeather.WeatherType dayType = weatherItem.getE_day_type();
            if (dayType != null) {
                if (dayType == EABleWeather.WeatherType.clear) {
                    holder.dayText.setText(getString(R.string.weather_type_clear));

                } else if (dayType == EABleWeather.WeatherType.cloudy) {
                    holder.dayText.setText(getString(R.string.weather_type_cloudy));
                } else if (dayType == EABleWeather.WeatherType.gloomy) {
                    holder.dayText.setText(getString(R.string.weather_type_gloomy));
                } else if (dayType == EABleWeather.WeatherType.drizzle) {
                    holder.dayText.setText(getString(R.string.weather_type_drizzle));
                } else if (dayType == EABleWeather.WeatherType.moderate_rain) {
                    holder.dayText.setText(getString(R.string.weather_type_moderate_rain));
                } else if (dayType == EABleWeather.WeatherType.thunderstorm) {
                    holder.dayText.setText(getString(R.string.weather_type_thunderstorm));
                } else if (dayType == EABleWeather.WeatherType.heavy_rain) {
                    holder.dayText.setText(getString(R.string.weather_type_heavy_rain));
                } else if (dayType == EABleWeather.WeatherType.sleet) {
                    holder.dayText.setText(getString(R.string.weather_type_heavy_sleet));
                } else if (dayType == EABleWeather.WeatherType.light_snow) {
                    holder.dayText.setText(getString(R.string.weather_type_light_snow));
                } else if (dayType == EABleWeather.WeatherType.moderate_snow) {
                    holder.dayText.setText(getString(R.string.weather_type_moderate_snow));
                } else if (dayType == EABleWeather.WeatherType.heavy_snow) {
                    holder.dayText.setText(getString(R.string.weather_type_heavy_snow));
                }
            }
            holder.minTempText.setText(weatherItem.getMin_temperature() + "");
            holder.maxTempText.setText(weatherItem.getMax_temperature() + "");
            holder.humidityText.setText(weatherItem.getAir_humidity() + "");
            holder.windText.setText(weatherItem.getWind() + "");
            holder.scoreText.setText(weatherItem.getAir_grade() + "");
            holder.directionText.setText(weatherItem.getWindDirection().toString());
            holder.rainText.setText(weatherItem.getRain_pro() + "");
            holder.pmText.setText(weatherItem.getPm() + "");
            holder.stressText.setText(weatherItem.getPressure() + "");
            holder.uvText.setText(weatherItem.getUv() + "");


        }

        @Override
        public int getItemCount() {
            return eaBleWeather == null ? 0 : (eaBleWeather.getS_day() == null ? 0 : eaBleWeather.getS_day().size());
        }

        class HoldView extends RecyclerView.ViewHolder {
            TextView dayText;
            TextView minTempText;
            TextView maxTempText;
            TextView humidityText;
            TextView scoreText;
            TextView windText;
            TextView directionText;
            TextView uvText;
            TextView pmText;
            TextView rainText;
            TextView stressText;

            public HoldView(@NonNull AdapterTitanWeatherRecyclerviewBinding adapterTitanWeatherRecyclerviewBinding) {
                super(adapterTitanWeatherRecyclerviewBinding.getRoot());
                stressText = adapterTitanWeatherRecyclerviewBinding.stress;
                rainText = adapterTitanWeatherRecyclerviewBinding.rain;
                pmText = adapterTitanWeatherRecyclerviewBinding.pm;
                uvText = adapterTitanWeatherRecyclerviewBinding.uvIntensity;
                directionText = adapterTitanWeatherRecyclerviewBinding.windDirection;
                windText = adapterTitanWeatherRecyclerviewBinding.windPower;
                scoreText = adapterTitanWeatherRecyclerviewBinding.airScore;
                humidityText = adapterTitanWeatherRecyclerviewBinding.airHumidity;
                maxTempText = adapterTitanWeatherRecyclerviewBinding.maxTemperature;
                minTempText = adapterTitanWeatherRecyclerviewBinding.minTemperature;
                dayText = adapterTitanWeatherRecyclerviewBinding.daytimeWeather;
            }
        }
    }
}
